'use client'

import { useState, useCallback } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { cn } from '@/lib/utils'

interface ImagePreviewProps {
  src: string
  alt?: string
  className?: string
  children: React.ReactNode
}

export function ImagePreview({ src, alt = '', className, children }: ImagePreviewProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  const handleOpen = useCallback(() => {
    setIsOpen(true)
  }, [])



  const handleImageLoad = useCallback(() => {
    setIsLoading(false)
  }, [])

  const handleImageError = useCallback(() => {
    setIsLoading(false)
  }, [])

  return (
    <>
      <div 
        className={cn('cursor-pointer', className)} 
        onClick={handleOpen}
      >
        {children}
      </div>

      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] p-0">
          <DialogHeader className="p-4 border-b">
            <DialogTitle>Image Preview</DialogTitle>
            <DialogDescription>
              {alt}
            </DialogDescription>
          </DialogHeader>
          
          <div className="flex items-center justify-center p-4 min-h-[50vh]">
            {isLoading && (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
              </div>
            )}
            <img
              src={src}
              alt={alt}
              className={cn(
                'max-w-full max-h-[70vh] object-contain',
                isLoading ? 'opacity-0' : 'opacity-100'
              )}
              onLoad={handleImageLoad}
              onError={handleImageError}
            />
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}